import {getLoginStatus, qrKey, checkStatus, qrCreate} from "@src/services/music.ts"
import {useEffect, useState} from "react";
import {useRequest} from "ahooks";

const QrLogin = () => {

    const getLoginStatusApi = useRequest(getLoginStatus, {manual: true})
    const qrKeyApi = useRequest(qrKey, {manual: true})
    const qrCreateApi = useRequest(qrCreate, {manual: true})
    const checkStatusAPi = useRequest(checkStatus, {manual: true})

    const [info, setInfo] = useState<string>("正在加载")
    const [imgUrl, setImgUrl] = useState<string>("#")
    let timer: number | undefined;
    const login = async () => {

        const cookie = localStorage.getItem('cookie')
        await getLoginStatusApi.runAsync(JSON.stringify(cookie)).then((data) => {
            console.log("获取用户详细", data)
            setInfo(JSON.stringify(data.data))
        })

        const res = await qrKeyApi.runAsync().then(data => {
            return data
        })
        const key = res.data.unikey
        console.log(key, "1")
        await qrCreateApi.runAsync(key).then((data) => {
            setImgUrl(data.data.qrimg)
        })


        timer = setInterval(async () => {
            const statusRes = await checkStatusAPi.runAsync(key).then((data) => {
                return data
            })
            console.log(statusRes)
            if (statusRes.code === 800) {
                alert('二维码已过期,请重新获取')
                clearInterval(timer)
            }
            if (statusRes.code === 803) {
                // 这一步会返回cookie
                clearInterval(timer)
                alert('授权登录成功')
                await getLoginStatusApi.runAsync(JSON.stringify(statusRes.code)).then((data) => {
                    console.log("获取用户详细", data)
                    setInfo(JSON.stringify(data.data))
                })
                localStorage.setItem('cookie', statusRes.cookie)
            }
        }, 3000)

    }

    useEffect(() => {
        login().then()
        return () => {
            clearInterval(timer)
        }
    }, []);


    return <div>
        二维码
        <img src={imgUrl} width="200" height="200" alt=""/>
        {info}
    </div>
};

export default QrLogin;